package com.navi.loaddata.loadService.impl.EqEvent;

import com.navi.loaddata.core.mysqlEntity.EdaDiffD;
import com.navi.loaddata.core.mysqlEntity.EdaDiffDModel;
import com.navi.loaddata.core.mysqlEntity.EtlConfD;
import com.navi.loaddata.core.mysqlEntity.EtlConfDModel;
import com.navi.loaddata.core.oracleEntity.EtlEquipEventV;
import com.navi.loaddata.core.repository.impl.MesRepositoryImpl;
import com.navi.loaddata.core.util.JdbcUtil;
import com.navi.loaddata.core.util.LoggerUtil;
import com.navi.loaddata.core.util.ProcessUtil;
import com.navi.loaddata.loadService.impl.edaDifference.SaveEdaDiff;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xufan
 */
@Service
public class LoadEqStateService {
    private static final Logger logger = LoggerFactory.getLogger(LoadEqStateService.class);
    private LoggerUtil loggerUtil = new LoggerUtil(this.getClass());

    @Autowired
    private SaveEqState saveEqState;
    @Autowired
    private MesRepositoryImpl mesdao;

    public String[] loadEqStateDataMain(EtlConfDModel etlConfD) throws Exception {
        String[] resMsg=new String[3];

        try {
            resMsg = loadEqStateData(etlConfD);
            String msg=etlConfD.getEqpt();

            if(StringUtils.isEmpty(etlConfD.getOpe())) msg="ALL";
            logger.info("Eqpt={} loadEqStateMain finish!",msg);
        } catch (Exception e) {
            throw e;
        }
        return resMsg;
    }

    /**
     * Load Measure Data
     * <p>
     * load base -> session table
     * load defect data  -> session table
     * call base proc  -> auto commit
     * call defect proc -> no auto commit
     * delete defect session table
     *
     * @param etlConfD
     */
    private String[] loadEqStateData(EtlConfDModel etlConfD) throws Exception {
        String[] resMsg=new String[3];
        int okCnt = 0;
        int errCnt=0;
        String errMsg=null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Timestamp startTime=etlConfD.getRunStartTimestamp();
//        Timestamp endTime=etlConfD.getRunEndTimestamp();
        String start=etlConfD.getRunStartTimestamp().toString().substring(0,19);
        String end=etlConfD.getRunEndTimestamp().toString().substring(0,19);

        Timestamp updateTime = Timestamp.valueOf(LocalDateTime.now());

        QueryRunner qr_gp = JdbcUtil.getQueryRunner_mes();
        QueryRunner qr_ora = JdbcUtil.getQueryRunner_ora_edaldr();
        // gp mes data
        String sql="select " +
                " machinename as equipId," +
                " eventtime as eventStartTime," +
                " 'EQST' as eventCategory," +
                " MachineStateName as eventCode," +
                " MachineMainStateName as eventGroup," +
                " EventUser as eventUser" +
                " from mes_machinehistory " +
                " where subfactoryname = '"+etlConfD.getShop()+"'" +
                //没有OPE
                ProcessUtil.getEqptMesHql(etlConfD.getEqpt())+
                " and UPDATETIME >= to_date('"+start+"','yyyy-mm-dd hh24:mi:ss') " +
                " AND UPDATETIME <  to_date('"+end+"','yyyy-mm-dd hh24:mi:ss')" ;
        List<EtlEquipEventV> etlEquipEventVList = qr_gp.query(sql, new BeanListHandler<EtlEquipEventV>(EtlEquipEventV.class));
        logger.info("MES 机台概况数据量：{}",etlEquipEventVList.size());

        if(etlEquipEventVList.size()>0) {
            for(int i=0;i<etlEquipEventVList.size();i+=1000){
                Map<String,EtlEquipEventV> saveList = new HashedMap();
                for(int j=0;j<1000;j++){
                    if(i+j<etlEquipEventVList.size()) {
                        if (saveList.size() > 0 && null != saveList.get(etlEquipEventVList.get(i + j).getEquipId() + "_" + etlEquipEventVList.get(i + j).getEventCode() + "_" + etlEquipEventVList.get(i + j).getEventStartTime())) {
                            errCnt++;
                            continue;
                        }
                        saveList.put(etlEquipEventVList.get(i + j).getEquipId() + "_" + etlEquipEventVList.get(i + j).getEventCode() + "_" + etlEquipEventVList.get(i + j).getEventStartTime(), etlEquipEventVList.get(i + j));
                        okCnt++;
                    }
                }
                saveEqState.saveEqStateList1000(etlConfD,saveList);
                saveEqState.deleteEqStateList1000(etlConfD);
            }

        }

        resMsg[0]=String.valueOf(okCnt);
        resMsg[1]=String.valueOf(errCnt);
        resMsg[2]=errMsg;

        return resMsg;
    }

    public List<String> getEqpts(EtlConfD etlConfD){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String start=etlConfD.getRunStartTimestamp().toString().substring(0,19);
        String end=etlConfD.getRunEndTimestamp().toString().substring(0,19);

        String sql="select " +
                " DISTINCT machinename as equipId" +
                " from mes_machinehistory " +
                " where subfactoryname = '"+etlConfD.getShop()+"'" +
                " and UPDATETIME >= to_date('"+start+"','yyyy-mm-dd hh24:mi:ss') " +
                " AND UPDATETIME <  to_date('"+end+"','yyyy-mm-dd hh24:mi:ss')" ;
        List<String> eqpts = mesdao.findBySQL(sql);
        return eqpts;
    }
}
